# coding:utf-8

from . import api
from ihome.utils.commons import login_required
from flask import g, current_app, jsonify, request, session
from ihome.utils.response_code import RET
from ihome.models import User, UserToStudent, UserAddress, HouseCollection, House, Order, GoodsOrder
from ihome.utils.image_storage import storage
from ihome import db, constants
import os


@api.route("/users/avatar", methods=["POST"])
@login_required
def set_user_avatar():
    """设置用户的头像
    参数： 图片(多媒体表单格式)  用户id (g.user_id)
    """
    # 装饰器的代码中已经将user_id保存到g对象中，所以视图中可以直接读取

    # user_id = g.user_id

    # 获取图片

    image_file = request.files.get("image_file")
    print(image_file)

    if image_file is None:
        return jsonify(errno=RET.PARAMERR, errmsg="未上传图片")

    # 调用七牛云上传图片，返回文件名字
    image_data = image_file.read()

    try:
        file_name = storage(image_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传图片失败")

    # 不直接保存在数据库中，只保存到URL中
    # 保存图片路径到数据库中
    # try:
    #     User.query.filter_by(id=user_id).update({"avatar_url": file_name})
    #     db.session.commit()
    # except Exception as e:
    #     db.session.rollback()
    #     current_app.logger.error(e)
    #     return jsonify(errno=RET.DBERR, errmsg="保存图片信息失败")

    image_url = constants.QINIU_URL_DOMAIN + file_name

    return jsonify(errno=RET.OK, errmsg="保存成功", data={"image_url": image_url})


@api.route("/user/update", methods=["PUT"])
@login_required
def change_user_info():
    """更新个人信息"""

    user_id = g.user_id

    req_data = request.get_json()
    name = req_data.get("name")  # 昵称
    avatar_url = req_data.get("avatar_url")  # 头像存储
    sex = req_data.get("sex") if req_data.get("sex") is not None else 1  # 存储的值为数字 默认为女
    works = req_data.get('works') if req_data.get('words') is not None else ""  # 工作信息
    sign = req_data.get('sign') if req_data.get('sign') is not None else ""  # 个性签名
    # birthday = req_data.get('birthday') if req_data.get('birthday') is not None else ""  # 出身日期  可以为空
    education = req_data.get('education') if req_data.get('education') is not None else ""  # 教育背景

    # 保存用户信息到数据库
    try:
        User.query.filter_by(id=user_id).update(
            {"name": name, "avatar_url": avatar_url, "sex": sex, "education": education,
             "works": works, "sign": sign})
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据出现错误")

    # 修改session数据中的name字段
    session["name"] = name
    return jsonify(errno=RET.OK, errmsg="更新成功")


@api.route("/user/get_user", methods=["GET"])
@login_required
def get_user_info():
    """
    获取等当前登录的用户的所有信息
    :return:
    """
    user_id = g.user_id
    # 查询数据库获取个人信息
    try:
        user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取用户信息失败")

    # jsonify 将字典转化为jsonify
    return jsonify(errno=RET.OK, errmsg="获取成功", data=user.to_dict())


# 需要实名认证页面展示
@api.route("/user/auth_card", methods=["GET"])
@login_required
def get_user_auth_card():
    """获取当前用户的使实名认证信息"""
    user_id = g.user_id

    try:
        user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取用户实名信息失败")

    return jsonify(errno=RET.OK, errmsg="获取成功", data=user.auth_to_dict())


@api.route("/users/auth_card", methods=["POST"])
@login_required
def set_user_auth_card():
    """保存实名认证信息"""
    user_id = g.user_id

    req_data = request.get_json()
    if not req_data:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    real_name = req_data.get("real_name")  # 真实姓名
    id_card = req_data.get("id_card")  # 身份证号

    # 参数校验
    if not all([real_name, id_card]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 保存用户的姓名与身份证号
    try:
        User.query.filter_by(id=user_id, real_name=None, id_card=None) \
            .update({"real_name": real_name, "id_card": id_card})
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存用户实名信息失败")

    user = User.query.get(user_id)
    return jsonify(errno=RET.OK, errmsg="提交认证成功", data=user.auth_to_dict())


# 获取学生认证的信息
@api.route("/user/auth_student", methods=["GET"])
@login_required
def get_user_auth_student():
    """获取当前用户的使学生认证信息"""
    user_id = g.user_id
    try:
        student = UserToStudent.query.filter_by(user_id=user_id).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取用户学生信息失败")
    if student is None:
        return jsonify(errno=RET.NODATA, errmsg="不存在认证记录")

    return jsonify(errno=RET.OK, errmsg="获取成功", data=student.auth_to_dict())


@api.route("/users/auth_student", methods=["POST"])
@login_required
def set_user_auth_student():
    """保存学生认证信息"""
    user_id = g.user_id
    req_data = request.get_json()
    if not req_data:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    school = req_data.get("school")  # 学校名
    real_name = req_data.get("real_name")  # 真实姓名
    student_voucher_url = req_data.get("student_voucher_url")  # 认证凭证

    if not all([school, real_name, student_voucher_url]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    student_voucher = UserToStudent(
        user_id=user_id,
        school=school,
        real_name=real_name,
        student_voucher_url=student_voucher_url
    )

    try:
        db.session.add(student_voucher)
        # 认证成功后需要修改折扣
        User.query.filter_by(id=user_id).update(
            {"discount": "八"})
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存学生认证信息失败")

    return jsonify(errno=RET.OK, errmsg="保存成功")


@api.route("/users/get_address", methods=["GET"])
@login_required
def get_user_address():
    """获取当前登录的用户的所有的收货地址"""
    user_id = g.user_id
    try:
        address = UserAddress.query.filter_by(user_id=user_id).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取收货地址失败")
    if address is None:
        return jsonify(errno=RET.NODATA, errmsg="当前用户未添加收货地址")

    address_dict_li = []
    for item in address:
        address_dict_li.append(item.to_dict())

    return jsonify(errno=RET.OK, errmsg="获取成功", data=address_dict_li)


@api.route("/users/edit_address", methods=["GET"])
@login_required
def edit_user_address():
    """获取当前登录的用户的选中的收货地址"""
    user_id = g.user_id
    address_id = request.args.get('address_id')
    print(address_id)
    if address_id is None:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        address = UserAddress.query.filter_by(user_id=user_id, id=address_id).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取收货地址失败")

    if address is None:
        return jsonify(errno=RET.NODATA, errmsg="当前收货地址不存在")

    return jsonify(errno=RET.OK, errmsg="获取成功", data=address.to_dict())


@api.route("/users/delete_address", methods=["DELETE"])
@login_required
def del_user_address():
    """删除用户选中的一个地址"""
    user_id = g.user_id
    address_id = request.args.get('address_id')
    if address_id is None:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        address = UserAddress.query.filter_by(user_id=user_id, id=address_id).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取收货地址失败")

    if address is None:
        return jsonify(errno=RET.NODATA, errmsg="当前收货地址不存在")

    try:
        db.session.delete(address)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="取消失败")
    return jsonify(errno=RET.OK, errmsg="删除成功")


@api.route("/users/add_address", methods=["POST"])
@login_required
def add_user_address():
    """添加或更新当前登录的用户的收货地址"""

    user_id = g.user_id
    req_data = request.get_json()
    if not req_data:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    name = req_data.get("name")  # 收件人
    address = req_data.get("address")  # 详细地址
    phone = req_data.get("phone")  # 收件人联系方式
    address_id = req_data.get("address_id")  # 收货id

    if address_id is not None:
        try:
            UserAddress.query.filter_by(id=address_id) \
                .update({"name": name, "address": address, "phone": phone, })
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="获取收货地址失败")

        return jsonify(errno=RET.OK, errmsg="更新收货地址成功")

    if not all([name, address, phone]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    address = UserAddress(
        user_id=user_id,
        name=name,
        address=address,
        phone=phone
    )

    try:
        db.session.add(address)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存收货地址失败")

    return jsonify(errno=RET.OK, errmsg="保存成功")


@api.route("/users/get_user_collected", methods=["GET"])
@login_required
def get_user_collected():
    """获取当前登录用户收藏的房屋"""
    user_id = g.user_id
    try:
        collections = HouseCollection.query.filter_by(user_id=user_id).all()
        houses_ids = [collection.house_id for collection in collections]
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取收藏失败")
    if houses_ids is None:
        return jsonify(errno=RET.NODATA, errmsg="当前用户未收藏房屋")

    houses = House.query.filter(House.id.in_(houses_ids)).order_by(House.create_time.desc()).all()
    collected_dict_li = []
    if houses:
        for item in houses:
            collected_dict_li.append(item.to_basic_dict())

    return jsonify(errno=RET.OK, errmsg="获取成功", data=collected_dict_li)


@api.route("/users/del_user_collected", methods=["DELETE"])
@login_required
def del_user_collected():
    """获取删除用户收藏的房屋"""
    user_id = g.user_id
    # 获取参数
    house_id = request.args.get("house_id")

    print(type(house_id))

    if house_id.strip() == '':
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    del_collection = HouseCollection.query.filter_by(house_id=house_id, user_id=user_id).first()
    try:
        db.session.delete(del_collection)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="取消失败")
    return jsonify(errno=RET.OK, errmsg="删除成功")


@api.route("/users/get_my_lease", methods=["GET"])
@login_required
def get_my_lease():
    """获取我出租的房屋"""
    user_id = g.user_id
    try:
        house = House.query.filter_by(user_id=user_id).order_by(House.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取失败")
    if house is None:
        return jsonify(errno=RET.NODATA, errmsg="当前用户未出租房屋")

    try:
        house_count = House.query.filter_by(user_id=user_id).count()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取失败")
    if house is None:
        return jsonify(errno=RET.NODATA, errmsg="当前用户未出租房屋")

    house_dict_li = []
    for item in house:
        house_dict_li.append(item.to_basic_dict())

    return jsonify(errno=RET.OK, errmsg="获取成功", data={"house_count": house_count, "house_list": house_dict_li})


@api.route("/users/del_my_lease", methods=["DELETE"])
@login_required
def del_my_lease():
    """删除我出租的一个房屋"""
    # user_id = g.user_id
    # 获取参数
    house_id = request.args.get("house_id")

    print(type(house_id))

    if house_id.strip() == '':
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 判断用户是否已经收藏，如果已经收藏则返回
    del_lease = House.query.filter_by(id=house_id).first()
    try:
        db.session.delete(del_lease)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="删除失败")
    return jsonify(errno=RET.OK, errmsg="删除成功")


@api.route("/users/get_request_house", methods=["GET"])
@login_required
def get_request_house():
    """获取看房申请
        如果连表则链接量张表：
        House,Order
        不链表就查询两次
    """
    # 　查询当前用户发布的房屋
    user_id = g.user_id

    # 查询订单数据
    try:
        # 以房东的身份查询订单
        # 先查询属于自己的房子有哪些
        houses = House.query.filter(House.user_id == user_id).all()
        houses_ids = [house.id for house in houses]
        # 再查询预订了自己房子的订单
        orders = Order.query.filter(Order.house_id.in_(houses_ids)).order_by(Order.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询失败")

    orders_dict_list = []
    for order in orders:
        orders_dict_list.append(order.to_dict())

    return jsonify(errno=RET.OK, errmsg="查询成功", data=orders_dict_list)


@api.route("/users/get_my_goods", methods=["GET"])
@login_required
def get_my_goods():
    """获取我兑换的商品"""
    user_id = g.user_id
    try:
        goods = GoodsOrder.query.filter_by(user_id=user_id).order_by(GoodsOrder.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取失败")
    if goods is None:
        return jsonify(errno=RET.NODATA, errmsg="当前用户未兑换商品")

    goods_dict_li = []
    for item in goods:
        goods_dict_li.append(item.to_dict())

    return jsonify(errno=RET.OK, errmsg="获取成功", data=goods_dict_li)